﻿using DGSFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Framework.WebmasterTool.Questions
{
    public partial class QuestionAdd : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadData();
            }
        }
        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.Article.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void CallCkeditors()
        {
            Globals.CallCKFinder(txtQuestion);
        }
        public void LoadData()
        {
            if (Request.QueryString["ID"] != null)
            {
                pnAdd.Visible = true;
                pnUpdate.Visible = false;
                var id = 0;
                try
                {
                    id = int.Parse(Request.QueryString["ID"].ToString());
                }
                catch (Exception ex)
                {

                }
                if (id == 0)
                    //redirect page
                    Response.Redirect("Default.aspx");
                var data = entity.udv_Question.Include("udv_Answer").Where(d => d.ID == id).FirstOrDefault();
                if (data != null)
                {
                    txtTitle.Text = data.Title;
                    txtQuestion.Text = data.Question;
                    txtDisplayOrder.Text = data.DisplayOrder.HasValue?data.DisplayOrder.Value.ToString():"0";
                    if(!string.IsNullOrEmpty(data.FileURL))
                        ltAudio.Text = "<audio controls><source src='" + DGSFramework.Globals.ApplicationPath + "UserUpload/Questions/" + data.FileURL + "' type='audio/mpeg'></audio><br /><br />";
                    rptAnswer.DataSource = data.udv_Answer.OrderBy(d => d.DateCreate).ToList();
                    rptAnswer.DataBind();
                }
                else
                    Response.Redirect("Default.aspx");
            }
            else {
                pnAdd.Visible = false;
                pnUpdate.Visible = true;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] == null)
            {
                var question = new udv_Question();
                question.Title = txtTitle.Text;
                question.Question = txtQuestion.Text;
                question.DateCreate = DateTime.Now;
                question.UserCreate = Membership.GetUser().UserName;
                if (!string.IsNullOrEmpty(txtDisplayOrder.Text))
                    question.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                else
                    question.DisplayOrder = 0;
                if (VideoFile.HasFile)
                {
                    string strFileNameTemp = Globals.GetFileName(VideoFile.FileName);
                    VideoFile.SaveAs(Server.MapPath(ConfigPaths.Path_FileQuestion_Folder_MapPath + strFileNameTemp));
                    question.FileURL = strFileNameTemp;
                }
                entity.AddToudv_Question(question);
                var answerList = Request.Form.GetValues("Answer");                
                var correct = Request.Form["Correct"];
                for (int i = 0; i < answerList.Count(); i++)
                {
                    var answer = answerList[i].Trim();                    
                    if (!string.IsNullOrEmpty(answer))
                    {
                        var answerObject = new udv_Answer();
                        answerObject.Answer = answer;
                        answerObject.udv_Question = question;
                        answerObject.DateCreate = DateTime.Now;
                        answerObject.UserCreate = Membership.GetUser().UserName;
                        if (!string.IsNullOrEmpty(correct)&& correct == i.ToString())
                            answerObject.Correct = true;
                        entity.AddToudv_Answer(answerObject);
                    }
                }
                entity.SaveChanges();
                Response.Redirect("Default.aspx");
            }
            else
            {
                var id = 0;
                try
                {
                    id = int.Parse(Request.QueryString["ID"]);
                }
                catch (Exception ex)
                {

                }
                var question = entity.udv_Question.Where(d => d.ID == id).FirstOrDefault();
                if (question != null)
                {
                    var userName = Membership.GetUser().UserName;
                    question.Title = txtTitle.Text;
                    question.Question = txtQuestion.Text;
                    question.DateUpdate = DateTime.Now;
                    question.UserUpdate = userName;
                    if (!string.IsNullOrEmpty(txtDisplayOrder.Text))
                        question.DisplayOrder = int.Parse(txtDisplayOrder.Text);
                    if (VideoFile.HasFile)
                    {
                        string strFileNameTemp = Globals.GetFileName(VideoFile.FileName);
                        VideoFile.SaveAs(Server.MapPath(ConfigPaths.Path_FileQuestion_Folder_MapPath + strFileNameTemp));
                        question.FileURL = strFileNameTemp;
                    }
                    var lstAnswer = entity.udv_Answer.Where(d => d.udv_Question.ID == id);
                    //xoa cau tra loi cu
                    foreach (var item in lstAnswer)
                    {                        
                        entity.DeleteObject(item);
                    }
                    var answerList = Request.Form.GetValues("Answer");
                    var correct = Request.Form["Correct"];
                    for (int i = 0; i < answerList.Count(); i++)
                    {
                        var answer = answerList[i].Trim();
                        if (!string.IsNullOrEmpty(answer))
                        {
                            var answerObject = new udv_Answer();
                            answerObject.Answer = answer;
                            answerObject.udv_Question = question;
                            answerObject.DateCreate = DateTime.Now;
                            answerObject.UserCreate = Membership.GetUser().UserName;
                            if (!string.IsNullOrEmpty(correct) && correct == i.ToString())
                                answerObject.Correct = true;
                            entity.AddToudv_Answer(answerObject);
                        }
                    }
                    entity.SaveChanges();
                    Response.Redirect("Default.aspx");
                }
            }
        }
        
        protected void rptAnswer_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem != null && e.Item.FindControl("ltCorrect") != null)
            {
                var answer = (udv_Answer)e.Item.DataItem;
                var html = "<input type='radio' value='{1}' name='Correct' {0}/>";
                if (answer.Correct == true)
                    html = string.Format(html, "checked",e.Item.ItemIndex);
                else
                    html = string.Format(html, "", e.Item.ItemIndex);
                var ltCorrect = e.Item.FindControl("ltCorrect") as Literal;
                ltCorrect.Text = html;
            }
        }
    }
}